# polls/models.py
from django.db import models
from django.utils import timezone
import datetime

class Question(models.Model):
    question_text = models.CharField('问题内容', max_length=200)
    pub_date = models.DateTimeField('发布日期')
    end_date = models.DateTimeField('结束日期', null=True, blank=True)
    is_active = models.BooleanField('是否活跃', default=True)
    
    class Meta:
        verbose_name = '投票问题'
        verbose_name_plural = '投票问题'
        ordering = ['-pub_date']
    
    def __str__(self):
        return self.question_text
    
    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now
    
    def is_currently_active(self):
        now = timezone.now()
        if self.end_date:
            return self.pub_date <= now <= self.end_date
        return self.pub_date <= now
    
    @property
    def total_votes(self):
        return sum(choice.votes for choice in self.choice_set.all())
    
    @property
    def days_remaining(self):
        if self.end_date:
            delta = self.end_date - timezone.now()
            return max(0, delta.days)
        return None
    
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = '最近发布?'

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, verbose_name='所属问题')
    choice_text = models.CharField('选项内容', max_length=200)
    votes = models.IntegerField('得票数', default=0)
    
    class Meta:
        verbose_name = '投票选项'
        verbose_name_plural = '投票选项'
    
    def __str__(self):
        return self.choice_text
    
    @property
    def percentage(self):
        if self.question.total_votes > 0:
            return round((self.votes / self.question.total_votes) * 100, 1)
        return 0